package com.springboot.demo.limit;

import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Test;

import com.google.common.util.concurrent.RateLimiter;

/**
 * 固定速率请求
 *
 * @author supu
 * @date 2019-10-14 16:54
 **/
public class FixedRequestLimitDemo {
    @Test
    public void fixedRequestTest() {
        // 表示1秒内产生多少个令牌，即1秒内产生5个令牌，控制每200ms一个请求
        RateLimiter rateLimiter = RateLimiter.create(5);
        AtomicInteger counter = new AtomicInteger(0);

        for (int i = 0; i < 15; i++) {
            // 同时开启15个线程访问
            new Thread(() -> fixedRequest(rateLimiter, counter)).start();
        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void fixedRequest(RateLimiter rateLimiter, AtomicInteger counter) {
        double time = rateLimiter.acquire();
        if (time >= 0) {
            System.out.println("时间：" + time + " ,第 " + counter.incrementAndGet() + " 个业务处理");
        }
    }
}
